Telegram Group & Telegram Channel
🧠 Задача на внимание и знание подводных камней в Python

Что выведет данный код?

def make_funcs():
funcs = []
for i in range(3):
def wrapper(x=i):
return lambda: x
funcs.append(wrapper())
return funcs

a, b, c = make_funcs()
print(a(), b(), c())

Варианты ответа:

A) 0 1 2
B) 2 2 2
C) 0 0 0
D) Ошибка на этапе выполнения

Ответ: 0 1 2

📘 Объяснение:
🔹 Цикл for i in range(3) проходит по значениям 0, 1, 2.

🔹 В каждой итерации вызывается wrapper(x=i) — это копирует текущее значение i в локальную переменную x.

🔹 Затем возвращается lambda: x, которая запоминает это конкретное значение x.

🔹 В итоге:

a() → 0

b() → 1

c() → 2

Если бы мы не использовали x=i по умолчанию, а написали просто lambda: i, все функции замкнули бы одну и ту же переменную i, и на момент вызова она бы уже была равна 3.

@Python_Community_ru



tg-me.com/Python_Community_ru/2557
Create:
Last Update:

🧠 Задача на внимание и знание подводных камней в Python

Что выведет данный код?

def make_funcs():
funcs = []
for i in range(3):
def wrapper(x=i):
return lambda: x
funcs.append(wrapper())
return funcs

a, b, c = make_funcs()
print(a(), b(), c())

Варианты ответа:

A) 0 1 2
B) 2 2 2
C) 0 0 0
D) Ошибка на этапе выполнения

Ответ: 0 1 2

📘 Объяснение:
🔹 Цикл for i in range(3) проходит по значениям 0, 1, 2.

🔹 В каждой итерации вызывается wrapper(x=i) — это копирует текущее значение i в локальную переменную x.

🔹 Затем возвращается lambda: x, которая запоминает это конкретное значение x.

🔹 В итоге:

a() → 0

b() → 1

c() → 2

Если бы мы не использовали x=i по умолчанию, а написали просто lambda: i, все функции замкнули бы одну и ту же переменную i, и на момент вызова она бы уже была равна 3.

@Python_Community_ru

BY Python Community


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/Python_Community_ru/2557

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

Telegram has exploded as a hub for cybercriminals looking to buy, sell and share stolen data and hacking tools, new research shows, as the messaging app emerges as an alternative to the dark web.An investigation by cyber intelligence group Cyberint, together with the Financial Times, found a ballooning network of hackers sharing data leaks on the popular messaging platform, sometimes in channels with tens of thousands of subscribers, lured by its ease of use and light-touch moderation.

Spiking bond yields driving sharp losses in tech stocks

A spike in interest rates since the start of the year has accelerated a rotation out of high-growth technology stocks and into value stocks poised to benefit from a reopening of the economy. The Nasdaq has fallen more than 10% over the past month as the Dow has soared to record highs, with a spike in the 10-year US Treasury yield acting as the main catalyst. It recently surged to a cycle high of more than 1.60% after starting the year below 1%. But according to Jim Paulsen, the Leuthold Group's chief investment strategist, rising interest rates do not represent a long-term threat to the stock market. Paulsen expects the 10-year yield to cross 2% by the end of the year. A spike in interest rates and its impact on the stock market depends on the economic backdrop, according to Paulsen. Rising interest rates amid a strengthening economy "may prove no challenge at all for stocks," Paulsen said.

Python Community from ua


Telegram Python Community
FROM USA